<template>
  <div v-loading="loading" class="app-container" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
    <el-card class="box-card" style="float: left;width: 25%">
      <div slot="header" class="clearfix">
        <span>个人信息</span>
      </div>
      <div style="text-align: center">
        <img :src="avatar+'?imageView2/1/w/80/h/80'" style="border-radius: 100px;" @click="updateavatar">
        <br>
        <font size="5">{{ userInfo.name }}</font>
        <br><br>
        <span v-for="r in userInfo.role" :key="r">
          {{ r }}
        </span>
        <br>
        <div style="margin-top: 20px;margin-right: 20px; ">
          <table style="margin: auto;border-spacing: 20px;border-collapse: separate;">
            <tr>
              <td><svg-icon icon-class="sex" /></td>
              <td>{{ userInfo.sex ? '女':'男' }}</td>
            </tr>
            <tr>
              <td><svg-icon icon-class="phone" /> </td>
              <td>{{ userInfo.phone === null || userInfo.phone === '' ? '请绑定手机':userInfo.phone }}</td>
            </tr>
            <tr>
              <td><svg-icon icon-class="email" /> </td>
              <td>{{ userInfo.email === null || userInfo.email === '' ? '请绑定邮箱':userInfo.email }}</td>
            </tr>
            <tr>
              <td><svg-icon icon-class="address" /> </td>
              <td>{{ userInfo.address }}</td>
            </tr>
            <tr>
              <td><svg-icon icon-class="time" title="注册时间" /> </td>
              <td>{{ userInfo.createTime }}</td>
            </tr>
          </table>
        </div>
      </div>
    </el-card>
    <el-card class="box-card" style="float: left;margin-left: 20px;width: 70%;">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="用户信息" name="user">
          <el-form label-width="80px">
            <el-form-item label="账号">
              <span>{{ userInfo.username }}</span>
            </el-form-item>
            <el-form-item label="昵称">
              <el-input v-model="userInfo.name" style="width: 220px" />
            </el-form-item>
            <el-form-item label="性别">
              <el-switch
                v-model="userInfo.sex"
                :active-value="false"
                :inactive-value="true"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="男"
                inactive-text="女"
              />
            </el-form-item>
            <el-form-item label="手机">
              <el-input v-model="userInfo.phone" style="width: 220px" disabled />
              <el-button type="text" round @click="updatePhone">修改手机</el-button>
              <template v-if="btnp.uphone">
                <br><br>
                <el-input v-if="!btnp.newPhoneYznmShow" v-model="btnp.newPhone" maxlength="11" placeholder="请输入手机号码" style="width: 220px" />
                <el-input v-if="btnp.newPhoneYznmShow" v-model="btnp.newPhoneYznm" maxlength="6 " placeholder="请输入6位验证码" style="width: 150px" />
                <el-button type="text" round :disabled="btnp.sendMsgDisabled" @click="uphoneyzmbtn" v-text="btnp.pyzmtext" />
                <br><br>
                <el-button v-if="btnp.savebtn" type="primary" round @click="uphonebtn">确定修改</el-button>
              </template>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="userInfo.email" style="width: 220px" disabled />
              <el-button type="text" round @click="upemailbtn">修改邮箱</el-button>
              <template v-if="btne.upEmail">
                <br><br>
                <el-input v-if="!btne.newEmailYznmShow" v-model="btne.newEmail" placeholder="请输入邮箱地址" style="width: 220px" />
                <el-input v-if="btne.newEmailYznmShow" v-model="btne.newEmailYznm" maxlength="6 " placeholder="请输入6位验证码" style="width: 150px" />
                <el-button type="text" round :disabled="btne.sendMsgDisabled" @click="upEmailyzmbtn" v-text="btne.eyzmtext" />
                <br><br>
                <el-button v-if="btne.savebtn" type="primary" round @click="upEmailbtn">确定修改</el-button>
              </template>
            </el-form-item>
            <el-form-item label="地址">
              <v-distpicker
                :province="address.province"
                :city="address.city"
                :area="address.area"
                @province="onChangeProvince"
                @city="onChangeCity"
                @area="onChangeArea"
              />
            </el-form-item>
            <el-form-item label="签名">
              <el-input
                v-model="userInfo.remarks"
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 6}"
                show-word-limit
                maxlength="500"
                placeholder="请输入内容"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" round @click="saveUserInfo">保存信息</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="第三方账号" name="threeAcc" v-loading="loading">
          <el-button type="primary" v-if="oauth.qq" round @click="userOauth(qq)">绑定 QQ </el-button>
          <el-button type="primary" v-if="oauth.gitee" round @click="userOauth(gitee)">绑定 Gitee</el-button>
          <el-table :data="threeAcc" style="width: 98%">
            <el-table-column prop="id" label="id" v-if="false"/>
            <el-table-column prop="platformType" label="三方平台类型"/>
            <el-table-column prop="platformName" label="三方账号昵称"/>
            <el-table-column prop="createTime" label="绑定时间"/>
            <el-table-column label="操作" width="220px">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" style="margin-top: 10px" @click="untying(scope.$index, scope.row)">解绑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="操作记录" name="second">
          <el-table
            :data="secondTableData"
            stripe
            style="width: 98%">
            <el-table-column prop="username" label="账号"/>
            <el-table-column prop="description" label="操作信息"/>
            <el-table-column prop="ip" label="操作IP"/>
            <el-table-column prop="startTime" :formatter="startTimeSecond" label="操作时间"/>
          </el-table>
          <el-pagination
            style="width: 90%;"
            :current-page="tablePage.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="tablePage.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tablePage.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import VDistpicker from 'v-distpicker'
import { removeToken, removeExp } from '@/utils/auth'
import { isUpdateUserInfo, obtainPhoneCode, updatePhone, obtainEmailCode, updateEmail, getAccInfo, untyingOauthInfoUser, getWebLog } from '@/api/user'
export default {
  name: 'Info',
  components: { VDistpicker },
  data() {
    return {
      loading: true,
      userInfo: {},
      threeAcc: [],
      secondTableData: [],
      activeName: 'user',
      oauth:{
        qq : true,
        gitee: true
      },
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      btnp: {
        newPhone: '',
        uphone: false,
        newPhoneYznmShow: false,
        newPhoneYznm: '',
        sendMsgDisabled: false,
        savebtn: false,
        pyzmtext: '获取验证码',
        timer: null,
        time: 300
      },
      btne: {
        newEmail: '',
        upEmail: false,
        newEmailYznmShow: false,
        newEmailYznm: '',
        sendMsgDisabled: false,
        savebtn: false,
        eyzmtext: '获取验证码',
        timer: null,
        time: 60
      },
      address: {
        province: '北京市',
        city: '北京城区',
        area: '东城区'
      }
    }
  },
  computed: {
    ...mapGetters([
      'avatar',
      'name',
      'roles',
      'user',
      'qq',
      'gitee'
    ])
  },
  created() {
    this.userInfo = this.user.user
    const city = this.userInfo.address.split('-')
    this.address.province = city[0]
    this.address.city = city[1]
    this.address.area = city[2]
    this.userInfo.phone = (this.userInfo.phone === null || this.userInfo.phone === '' ? '点击右侧绑定手机' : this.userInfo.phone)
    this.userInfo.email = (this.userInfo.email === null || this.userInfo.email === '' ? '点击右侧绑定邮箱' : this.userInfo.email)
    this.loading = false
  },
  methods: {
    handleClick(tab, event) {
      if (tab.name === 'threeAcc'){
        this.getAccInfo()
      } else if(tab.name === 'second'){
        this.getOperation()
      }
    },
    getAccInfo(){
      this.loading = true
      Object.assign(this.$data.oauth,this.$options.data().oauth)
      getAccInfo().then(res => {
        this.threeAcc = res.data.data
        const that = this
        this.threeAcc.forEach(function(k) {
          if (k.platformType == 'QQ'){
            that.oauth.qq = false
          } else if (k.platformType == 'GITEE'){
            that.oauth.gitee = false
          }
        })
        this.loading = false
      })
    },
    getOperation(){
      getWebLog({
        page: this.tablePage.currentPage,
        pageSize: this.tablePage.pageSize
      }).then(res => {
        this.tablePage.total = res.data.data.total
        this.secondTableData = res.data.data.records
        this.loading = false
      })
    },
    handleSizeChange: function(pageSize) {
      // 每页条数切换
      this.tablePage.pageSize = pageSize
      this.handleCurrentChange(this.tablePage.currentPage)
    },
    handleCurrentChange: function(currentPage) {
      this.loading = true
      // 页码切换
      this.tablePage.currentPage = currentPage
      this.getOperation()
    },
    onChangeProvince(a) {
      this.address.province = a.value
    },
    onChangeCity(a) {
      this.address.city = a.value
    },
    onChangeArea(a) {
      this.address.area = a.value
    },
    updateavatar() {
      this.$message.error('头像更换，暂未开放')
    },
    saveUserInfo() {
      this.loading = true
      this.userInfo.address = this.address.province + '-' + this.address.city + '-' + this.address.area
      isUpdateUserInfo(this.userInfo).then(res => {
        this.$message.success(res.data.msg)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    updatePhone() {
      this.btnp.uphone = true
      this.btnp.newPhoneYznmShow = false
    },
    uphoneyzmbtn: function() {
      const phone = this.btnp.newPhone
      if (!phone) {
        this.$message.error('手机号码不能为空')
      } else if (!/^1[3|4|5|6|7|8]\d{9}$/.test(phone)) {
        this.$message.error('手机号格式不正确')
      } else {
        this.btnp.newPhoneYznmShow = true
        this.btnp.savebtn = true
        this.btnp.sendMsgDisabled = true
        const that = this
        this.btnp.timer = setInterval(function() {
          if (that.btnp.time > 0) {
            that.btnp.time--
            that.btnp.pyzmtext = that.btnp.time + '秒后重新获取,验证码已发生至预留手机，请注意查收'
          } else {
            that.phoneStop(that.btnp.timer)
          }
        }, 1000)
        obtainPhoneCode({ phone: this.btnp.newPhone }).then(res => {
          this.$message.success(res.data.msg)
        }).catch(() => {
          this.phoneStop(this.btnp.timer)
        })
      }
    },
    uphonebtn() {
      const code = this.btnp.newPhoneYznm
      if (code === '' || code.length !== 6) {
        this.$message.error('验证码格式不正确')
      } else {
        this.loading = true
        updatePhone({ phone: this.btnp.newPhone, code: code }).then(res => {
          this.$message.success(res.data.msg)
          this.loading = false
          window.location.reload()
        }).catch(() => {
          this.loading = false
        })
      }
    },
    phoneStop(data) {
      this.btnp.sendMsgDisabled = false
      this.btnp.pyzmtext = '获取验证码'
      this.btnp.time = 300
      clearInterval(data)
    },
    upemailbtn() {
      this.btne.upEmail = true
      this.btne.newEmailYznmShow = false
    },
    upEmailyzmbtn() {
      const email = this.btne.newEmail
      if (!email) {
        this.$message.error('请输入邮箱地址')
      } else if (!/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email)) {
        this.$message.error('邮箱地址格式错误')
      } else {
        this.btne.savebtn = true
        this.btne.newEmailYznmShow = true
        this.btne.sendMsgDisabled = true
        const that = this
        this.btne.timer = setInterval(function() {
          if (that.btne.time > 0) {
            that.btne.time--
            that.btne.eyzmtext = that.btne.time + '秒后重新获取,验证码已发生至预留邮箱，请注意查收'
          } else {
            that.emailStop(that.btne.timer)
          }
        }, 1000)
        obtainEmailCode({ email: this.btne.newEmail }).then(res => {
          this.$message.success(res.data.msg)
        }).catch(() => {
          this.emailStop(this.btne.timer)
        })
      }
    },
    upEmailbtn() {
      const code = this.btne.newEmailYznm
      if (code === '' || code.length !== 6) {
        this.$message.error('验证码格式不正确')
      } else {
        this.loading = true
        updateEmail({ email: this.btne.newEmail, code: code }).then(res => {
          this.$message.success(res.data.msg)
          this.loading = false
          window.location.reload()
        }).catch(() => {
          this.loading = false
        })
      }
    },
    emailStop(data) {
      this.btne.sendMsgDisabled = false
      this.btne.eyzmtext = '获取验证码'
      this.btne.time = 60
      clearInterval(data)
    },
    untying(index,row){
      this.$confirm('此操作将解绑 '+row.platformType+' , 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        untyingOauthInfoUser(row).then( res => {
          this.$message.success(res.data.msg)
          this.getAccInfo()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    userOauth(url){
      removeToken()
      removeExp()
      window.location.href = url
    },
    startTimeSecond(row){
      let date = new Date(parseInt(row.startTime));
      let Y = date.getFullYear() + '-'
      let M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) + '-' : date.getMonth() + 1 + '-'
      let D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' '
      let h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':'
      let m = date.getMinutes()  < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':'
      let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      return Y + M + D + h + m + s
    }
  }
}
</script>

<style>
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 480px;
  }
</style>
